package com.hjj.dataStructures.stack;


import java.util.Scanner;

/**
 * @author hjj
 * @create 2019-11-17 23:08
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        // 测试一下ArrayStack是否正确
        // 先创建一个ArrayStack对象
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);
        while (loop) {
            System.out.println("show: 表示显示栈");
            System.out.println("exit: 退出程序");
            System.out.println("push: 添加数据到栈");
            System.out.println("pop: 从栈取出数据");
            System.out.println("请输入你的选择：");
            switch (scanner.next()){
                case "show":
                    stack.list();
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int value =  scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    int result = stack.pop();
                    System.out.println("出栈的数据是：" + result);
                    break;
                default:
                    break;
            }
        }
    }
}

/**
 * 定义一个用Array模拟的栈
 */
class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1; // top表示栈顶，初始化为-1

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }

    public boolean isFull() {
        if (top == (maxSize - 1)) {
            System.out.println("栈满");
            return true;
        } else {
            return false;
        }
    }

    public boolean isEmpty() {
        if (top == -1) {
            System.out.println("栈空");
            return true;
        } else {
            return false;
        }

    }

    /**
     * 入栈
     *
     * @param value
     */
    public void push(int value) {
        if (isFull()) return;
        top++;
        stack[top] = value;
    }

    /**
     * 出栈
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) return -1;
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 显示栈的情况【遍历栈】
     */
    public void list() {
        if (isEmpty()) return;
        // 需要从栈顶开始显示数据
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
}













